import React, { useState, useEffect } from 'react';
import { Ret, Title, useHigh, MainView, PanelTitle, BtGroup, BtToggle, d_sort, obj_str_trim, to_float, is_empty, loc } from 'sui';
import { load_supply, load_col } from '../../cmd';
import { GtBallView } from './gtball';
import { GtStdView } from './gtstd';
import { GtSumView } from './gtsum';

const GTview = ({ mod, data, title, hreturn }) => {
    const [cens_type, tpCens] = useState("std");
    const [map_supply, mapSupply] = useState();
    const [lst_ball, lstBall] = useState();
    const [lst_std, lstStd] = useState();
    const [col, setCol] = useState();
    const [high] = useHigh(220, 100);

    useEffect(() => {
        load_col(mod, setCol);
        load_supply(mod, null, mapSupply);
    }, [mod]);

    useEffect(() => {
        if (is_empty(data)) {
            return null;
        }

        const set_ball = new Set();
        const set_std = new Set();

        const t_ball = [];
        const t_std = [];

        data.forEach(d => {
            const ball = to_float(obj_str_trim(d, "ball"));
            const std = to_float(obj_str_trim(d, "std"));

            if (!set_ball.has(ball)) {
                t_ball.push({ sn: ball, name: ball });
                set_ball.add(ball);
            }

            if (!set_std.has(std)) {
                t_std.push({ sn: std, name: std });
                set_std.add(std);
            }
        });

        d_sort(t_ball, "sn");
        d_sort(t_std, "sn");

        t_ball.forEach(d => d["sn"] = "" + d["sn"]);
        t_std.forEach(d => d["sn"] = "" + d["sn"]);

        lstBall(t_ball);
        lstStd(t_std);
    }, [data]);

    const getView = () => {
        if (cens_type === "std") {
            return <GtStdView mod={mod} title={title} map_supply={map_supply} lst_ball={lst_ball} lst_std={lst_std} col={col} high={high}/>;
        } else if (cens_type === "sum") {
            return <GtSumView mod={mod} title={title} high={high}/>;
        }

        return <GtBallView mod={mod} title={title} map_supply={map_supply} lst_ball={lst_ball} col={col} high={high}/>;
    };

    const Right = () => (
        <div className="inline-flex">
            <Ret hcmd={hreturn}/>
        </div>
    );

    const Left = () => {
        return (
            <div className="inline-flex items-center">
                <Title mod={loc("l_793")} sub={title} className="mr-32"/>
                <BtGroup value={cens_type} exclusive onChange={(e, v) => tpCens(v)}>
                    <BtToggle value="std">{loc("l_827")}</BtToggle>
                    <BtToggle value="tba">{loc("l_828")}</BtToggle>
                    <BtToggle value="sum">{loc("l_836")}</BtToggle>
                </BtGroup>
            </div>
        );
    };

    return (
        <MainView>
            <PanelTitle left={<Left/>} right={<Right/>} cl="gray"/>
            {getView()}
        </MainView>
    );
};

export {GTview};
